package com.team.est.service.impl;

import com.team.est.dto.BrandDto;
import com.team.est.dto.ClassifyDto;
import com.team.est.dto.ModelDto;
import com.team.est.mapper.BrandMapper;
import com.team.est.mapper.ClassifyMapper;
import com.team.est.mapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author 樊浩
 * @version 1.0
 * @description: TODO
 * @date 2021/3/2 11:44
 */
@RestController
@RequestMapping("/classify/")
public class ClassifyServiceImpl {

 @Autowired
 private RedisTemplate redisTemplate;

 @Autowired(required = false)
 private ClassifyMapper classifyMapper;

 @Autowired(required = false)
 private BrandMapper brandMapper;

 @Autowired(required = false)
 private ModelMapper modelMapper;
//返回分类树
 @RequestMapping("getClassifyTress")
 public List<ClassifyDto> getClassifyTree(){

  ValueOperations<String,List<ClassifyDto>> vo = redisTemplate.opsForValue();
  List<ClassifyDto> classifyDtos=null;
  //判断Redis服务器中是否存在缓存树
  if (redisTemplate.hasKey("classTree")){
   classifyDtos=vo.get("classTree");
   System.out.println("我是从缓存中获取的数据.........");
  }else {
   classifyDtos = this.classifyMapper.getAllClassifyDto();
   //第一步:查询所有的分类信息
   //调用dao层查询所有分类
   //第二步:循环每个分类，通过分类的id查找对应的品牌
   for (ClassifyDto classifyDto : classifyDtos) {
    //通过类别id查询品牌
    List<BrandDto> brandDtos = brandMapper.getBrandByClassifyId(classifyDto.getId());

    //第三步:循环每个品牌，通过品牌的id查找对应的商品
    for (BrandDto brandDto : brandDtos) {
     //通过品牌的id查询商品
     List<ModelDto> modelDtos = modelMapper.selectModelByBrandId(brandDto.getId());
     //将商品添加到品牌实体
     brandDto.setModelList(modelDtos);
    }
    classifyDto.setBrandList(brandDtos);  //给分类添加品牌
   }
   //从数据中获取分类数据--结束
   System.out.println("我是从数据库中获取的数据.........");
   //将分类树的数据保存到Redis
   vo.set("classTree",classifyDtos,20,TimeUnit.MINUTES);
  }
  return classifyDtos;
 }
}
